import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter_cookbook/ui/pages/DetailPage.dart';
import 'package:flutter_cookbook/utils/MsgUtil.dart';
import 'package:flutter_cookbook/utils/UrlUtil.dart';

var _name;
var _classid;
var _context;
var _start;
var loading = false;

class CookbookListPage extends StatelessWidget {

  final name;

  final classid;

  CookbookListPage(this.name, this.classid) {
    _name = name;
    _classid = classid;
    _start = 0;
    loading = false;
  }

  @override
  Widget build(BuildContext context) {
    _context = context;

    return MaterialApp(
      home: new MyList(),
    );
  }

}

class MyList extends StatefulWidget {
  
  @override
  State<StatefulWidget> createState() {
    return _MyList();
  }
  
}

class _MyList extends State {

  static const loadingTag = "##loading##"; //表尾标记

  List _list = [loadingTag];

  bool loadFinish = false;

  HttpClient httpClient;

  Widget none = Center(
    child: Text("什么都没有！"),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        brightness: Brightness.dark,
        centerTitle: true,
        title: Text(_name),
        leading: IconButton(
            onPressed: () {
              Navigator.of(_context).pop();
            },
            icon: Icon(Icons.arrow_back)
        ),
      ),
      body: _list.length == 1 ? none : ListView.builder(
        physics: BouncingScrollPhysics(),
        itemBuilder: (BuildContext context, int index) {
          //print(_list[index]);

          if (_list[index] == loadingTag) {
            // print(loadFinish);
              if (loadFinish) {
                return Container(
                    alignment: Alignment.center,
                    padding: EdgeInsets.all(16.0),
                    child: Text("没有更多了", style: TextStyle(color: Colors.grey),)
                );
              } else {
                if (!loading) {
                  _start += 10;
                  getData();
                }

                return Container(
                  padding: const EdgeInsets.all(16.0),
                  alignment: Alignment.center,
                  child: SizedBox(
                      width: 24.0,
                      height: 24.0,
                      child: CircularProgressIndicator(strokeWidth: 2.0)
                  ),
                );
              }
          }

          return GestureDetector(
            onTap: () {
              // print(_list[index]);
              Navigator.of(_context).push(MaterialPageRoute(builder: (context) {
                return new DetailPage(_list[index]);
              }));
            },
            child: Container(
              color: Colors.transparent,
              padding: EdgeInsets.only(left: 8, top: 4, right: 8, bottom: 4),
              child: Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: ClipRRect(
                        child: Image(
                          image: NetworkImage(_list[index]["pic"]),
                        ),
                        borderRadius: BorderRadius.circular(5)
                    ),
                  ),
                  Expanded(
                    flex: 5,
                    child: Container(
                      margin: EdgeInsets.only(left: 8),
                      child: Column(
                        children: [
                          Text(
                            _list[index]["name"],
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Text(_list[index]["peoplenum"]),
                          Text(_list[index]["cookingtime"]),
                          Text(
                            _list[index]["tag"],
                            overflow: TextOverflow.ellipsis,
                          )

                        ],
                        crossAxisAlignment: CrossAxisAlignment.start,
                      ),
                    )
                  )
                ],
                crossAxisAlignment: CrossAxisAlignment.start,
              ),
            ),
          );
        },
        itemCount: _list.length,
      ),
    );
  }

  @override
  void initState() {
    super.initState();

    httpClient = new HttpClient();

    getData();
  }

  @override
  void dispose() {
    super.dispose();

    httpClient.close();
  }

  void getData() async {
    //String json = await loadData();

    loading = true;

    try {
      Uri url;

      if (_classid < 0) {
        url = Uri(scheme: "https",
            host: UrlUtil.host,
            path: UrlUtil.search,
            queryParameters: {
              "appkey": UrlUtil.appkey,
              "keyword": _name.toString(),
              "start": _start.toString(),
              "num": UrlUtil.num
            });
      } else {
        url = Uri(scheme: "https",
            host: UrlUtil.host,
            path: UrlUtil.byclass,
            queryParameters: {
              "appkey": UrlUtil.appkey,
              "classid": _classid.toString(),
              "start": _start.toString(),
              "num": UrlUtil.num
            });
      }

      HttpClientRequest request = await httpClient.postUrl(url);

      HttpClientResponse response = await request.close();

      String json = await response.transform(utf8.decoder).join();

      var result = jsonDecode(json);
      // print(result["status"]);

      setState(() {
        if (result["status"].toString() == MsgUtil.ok) {
          _list.insertAll(_list.length - 1, result["result"]["list"]);
        } else if (result["status"].toString() == MsgUtil.noMsg) {
          loadFinish = true;
        }
      });
    } catch (e) {
      // print(e.toString());
      if(_start >= 10) {
        _start -= 10;
      }
    }

    loading = false;
  }

}